<?php

/**
 * categoria actions.
 *
 * @package    catalogo
 * @subpackage categoria
 * @author     idirocco
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class categoriaActions extends sfActions
{

  /**
   * Listado x cat
   */
  public function executeShow(sfWebRequest $request)
  {
    // sorting
    if ($request->getParameter('sort') && $this->isValidSortColumn($request->getParameter('sort')))
    {
      $this->setSort(array($request->getParameter('sort'), $request->getParameter('sort_type')));
    }
  	
    $this->categoria = $this->getRoute()->getObject(); 

	  $this->pager = new sfDoctrinePager(
	    'Articulo',
	    sfConfig::get('app_cant_anuncios_cat')
	  );
	  
	  $this->pager->setQuery($this->categoria->getArticulosActivosQuery($this->getSort()));
	  $this->pager->setPage($request->getParameter('page', 1));
	  $this->pager->init();
	  
    $this->sort = $this->getSort();
    
  }

  protected function addSortQuery($query)
  {
    if (array(null, null) == ($sort = $this->getSort()))
    {
      return;
    }
 
    if (!in_array(strtolower($sort[1]), array('asc', 'desc')))
    {
      $sort[1] = 'asc';
    }

    $query->addOrderBy($sort[0] . ' ' . $sort[1]);
  }

  protected function getSort()
  {
    if (null !== $sort = $this->getUser()->getAttribute('articulo.sort', null, 'cat_module'))
    {
      return $sort;
    }

    $this->setSort(array(sfConfig::get('app_default_sort_cat_field'), sfConfig::get('app_default_sort_cat_type')));

    return $this->getUser()->getAttribute('articulo.sort', null, 'cat_module');
  }

  protected function setSort(array $sort)
  {
    if (null !== $sort[0] && null === $sort[1])
    {
      $sort[1] = 'asc';
    }

    $this->getUser()->setAttribute('articulo.sort', $sort, 'cat_module');
  }

  protected function isValidSortColumn($column)
  {
    return Doctrine_Core::getTable('Articulo')->hasColumn($column);
  }  
}
